#include "crc16.h"

Crc16::Crc16() : value(0xffff)
{

}

void Crc16::reset()
{
	value = 0xffff;
}

void Crc16::update(unsigned char const* data, size_t len)
{
	if (!data || len == 0) {
		return;
	}
	update(data, 0, len);
}

void Crc16::update(unsigned char const* data, size_t pos, size_t len)
{
	if (!data || len == 0) {
		return;
	}
	for (size_t i = pos; i < pos + len; ++i) {
		value ^= data[i];
		for (int j = 0; j < 8; ++j) {
			int bitL = value & 0x01;
			value >>= 1;
			if (bitL == 1) {
				value ^= 0xA001;
			}
		}
	}
}

unsigned short Crc16::getCrcValue()
{
	int h = (value & 0xff00) >> 8;
	int l = value & 0x00ff;
	return (l<<8)|h;
}
